package com.huan.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huan.reggie.common.BaseContext;
import com.huan.reggie.common.R;
import com.huan.reggie.pojo.Orders;
import com.huan.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 订单分页查询
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, Long number, String beginTime,String endTime){
        Page<Orders> pageInfo = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.eq(number!=null,Orders::getNumber,number);
        lambdaQueryWrapper.orderByDesc(Orders::getOrderTime);

        if (beginTime!=null&&endTime!=null){
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime begin = LocalDateTime.parse(beginTime, df);
            LocalDateTime end = LocalDateTime.parse(endTime,df);
            lambdaQueryWrapper.between(Orders::getOrderTime,begin,end);
        }

        orderService.page(pageInfo,lambdaQueryWrapper);

        return R.success(pageInfo);
    }

    /**
     * 修改订单状态
     * @return
     */
    @PutMapping
    public R<String> updateStatus(@RequestBody Orders orders){
        orderService.updateStatus(orders);
        return R.success("订单状态修改成功");
    }

/*    *
     * C端订单分页查询
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize){
        Long userId = BaseContext.getCurrentId();

        Page<Orders> pageInfo = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Orders::getUserId,userId);

        orderService.page(pageInfo,lambdaQueryWrapper);

        return R.success(pageInfo);
    }
}